"use client"

import { useState, useEffect } from "react"
import { useParams, useRouter } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { 
  FolderOpen, 
  Plus, 
  Search, 
  Upload,
  ArrowLeft,
  File,
  FileImage,
  FileText,
  Download,
  Eye,
  MoreHorizontal,
  Edit,
  Trash2,
  FileArchive,
  FileVideo,
  FileAudio
} from "lucide-react"
import { cn } from "@/lib/utils"

interface Resource {
  _id: string
  name: string
  type: string
  category: string
  size: number
  url: string
  uploadedBy: string
  uploadedByName: string
  uploadedAt: string
  updatedAt: string
  projectId: string
  description?: string
  tags?: string[]
}

const resourceCategories = [
  { id: 'package', name: '包装指引', icon: FileText },
  { id: 'process', name: '加工指引', icon: FileText },
  { id: 'material', name: '物料变更通知', icon: FileText },
  { id: 'bom', name: 'BOM', icon: FileText },
  { id: 'report', name: '认证报告', icon: FileText },
  { id: 'test_report', name: '测试报告', icon: FileText },
  { id: 'test_guide', name: '测试指引', icon: FileText },
  { id: 'spec', name: '产品规格书', icon: FileText },
  { id: 'code', name: '代码', icon: FileArchive },
  { id: 'firmware', name: '烧录文件', icon: FileArchive },
  { id: 'structure', name: '结构', icon: FileImage },
  { id: 'customer', name: '客户文件', icon: FileText },
  { id: 'component', name: '元器件规格书', icon: FileText },
  { id: 'schematic', name: '原理图', icon: FileImage },
  { id: 'pcb', name: 'PCB', icon: FileImage },
  { id: 'manual', name: '作业指导书', icon: FileText }
]

const getFileIcon = (type: string) => {
  if (type.startsWith('image/')) return FileImage
  if (type.startsWith('video/')) return FileVideo
  if (type.startsWith('audio/')) return FileAudio
  if (type.includes('archive') || type.includes('zip') || type.includes('rar')) return FileArchive
  return FileText
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

export default function ProjectResourcesPage() {
  const params = useParams()
  const router = useRouter()
  const projectId = params.id as string
  
  const [resources, setResources] = useState<Resource[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState("")
  const [selectedCategory, setSelectedCategory] = useState("all")
  const [activeTab, setActiveTab] = useState("files")

  useEffect(() => {
    loadResources()
  }, [projectId])

  const loadResources = async () => {
    try {
      setLoading(true)
      const response = await fetch(`/api/projects/${projectId}/resources`)
      if (response.ok) {
        const resourcesData = await response.json()
        setResources(resourcesData)
      }
    } catch (error) {
      console.error('加载资源失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const filteredResources = resources.filter(resource => {
    const matchesSearch = resource.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         (resource.description && resource.description.toLowerCase().includes(searchTerm.toLowerCase()))
    const matchesCategory = selectedCategory === "all" || resource.category === selectedCategory
    
    return matchesSearch && matchesCategory
  })

  const getResourcesByCategory = (categoryId: string) => {
    return filteredResources.filter(resource => resource.category === categoryId)
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载资源中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 页面头部 */}
      <div className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <Button variant="ghost" size="sm" onClick={() => router.back()}>
                <ArrowLeft className="h-4 w-4" />
              </Button>
              <div>
                <h1 className="text-2xl font-bold text-gray-900">项目资料</h1>
                <p className="text-sm text-gray-500">管理项目相关的所有文件和资料</p>
              </div>
            </div>
            <div className="flex items-center space-x-2">
              <Button variant="outline">
                <Upload className="h-4 w-4 mr-2" />
                上传文件
              </Button>
              <Button>
                <Plus className="h-4 w-4 mr-2" />
                新建文件夹
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* 主要内容 */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
          <TabsList>
            <TabsTrigger value="files">文件管理</TabsTrigger>
            <TabsTrigger value="categories">分类浏览</TabsTrigger>
            <TabsTrigger value="recent">最近文件</TabsTrigger>
          </TabsList>

          {/* 文件管理标签页 */}
          <TabsContent value="files" className="space-y-6">
            {/* 搜索和筛选 */}
            <Card>
              <CardContent className="pt-6">
                <div className="flex flex-col sm:flex-row gap-4">
                  <div className="flex-1">
                    <div className="relative">
                      <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                      <Input
                        placeholder="搜索文件..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className="pl-10"
                      />
                    </div>
                  </div>
                  <select 
                    value={selectedCategory} 
                    onChange={(e) => setSelectedCategory(e.target.value)}
                    className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                  >
                    <option value="all">全部分类</option>
                    {resourceCategories.map(category => (
                      <option key={category.id} value={category.id}>{category.name}</option>
                    ))}
                  </select>
                </div>
              </CardContent>
            </Card>

            {/* 文件列表 */}
            <div className="space-y-4">
              {filteredResources.length === 0 ? (
                <Card>
                  <CardContent className="pt-12 pb-12">
                    <div className="text-center">
                      <FolderOpen className="h-12 w-12 mx-auto mb-4 text-gray-400" />
                      <h3 className="text-lg font-medium text-gray-900 mb-2">暂无文件</h3>
                      <p className="text-gray-500 mb-4">
                        {searchTerm || selectedCategory !== "all" 
                          ? "没有找到符合条件的文件" 
                          : "开始上传第一个文件来管理项目资料"
                        }
                      </p>
                      <Button>
                        <Upload className="h-4 w-4 mr-2" />
                        上传文件
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              ) : (
                filteredResources.map((resource) => {
                  const FileIcon = getFileIcon(resource.type)
                  return (
                    <Card key={resource._id} className="hover:shadow-md transition-shadow">
                      <CardContent className="pt-6">
                        <div className="flex items-center justify-between">
                          <div className="flex items-center space-x-4">
                            <div className="flex-shrink-0">
                              <FileIcon className="h-8 w-8 text-gray-400" />
                            </div>
                            <div className="flex-1 min-w-0">
                              <h3 className="text-sm font-medium text-gray-900 truncate">
                                {resource.name}
                              </h3>
                              <div className="flex items-center space-x-4 mt-1">
                                <span className="text-xs text-gray-500">
                                  {formatFileSize(resource.size)}
                                </span>
                                <Badge variant="outline" className="text-xs">
                                  {resourceCategories.find(c => c.id === resource.category)?.name || resource.category}
                                </Badge>
                                <span className="text-xs text-gray-500">
                                  {resource.uploadedByName || '未知用户'}
                                </span>
                                <span className="text-xs text-gray-500">
                                  {new Date(resource.uploadedAt).toLocaleDateString()}
                                </span>
                              </div>
                              {resource.description && (
                                <p className="text-sm text-gray-600 mt-1 truncate">
                                  {resource.description}
                                </p>
                              )}
                            </div>
                          </div>
                          
                          <div className="flex items-center space-x-2">
                            <Button variant="ghost" size="sm">
                              <Eye className="h-4 w-4" />
                            </Button>
                            <Button variant="ghost" size="sm">
                              <Download className="h-4 w-4" />
                            </Button>
                            <Button variant="ghost" size="sm">
                              <Edit className="h-4 w-4" />
                            </Button>
                            <Button variant="ghost" size="sm">
                              <Trash2 className="h-4 w-4" />
                            </Button>
                            <Button variant="ghost" size="sm">
                              <MoreHorizontal className="h-4 w-4" />
                            </Button>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  )
                })
              )}
            </div>
          </TabsContent>

          {/* 分类浏览标签页 */}
          <TabsContent value="categories" className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {resourceCategories.map((category) => {
                const categoryResources = getResourcesByCategory(category.id)
                const CategoryIcon = category.icon
                
                return (
                  <Card key={category.id} className="hover:shadow-md transition-shadow cursor-pointer">
                    <CardHeader className="pb-3">
                      <CardTitle className="flex items-center space-x-2">
                        <CategoryIcon className="h-5 w-5" />
                        <span className="text-lg">{category.name}</span>
                        <Badge variant="secondary">{categoryResources.length}</Badge>
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-2">
                        {categoryResources.slice(0, 3).map((resource) => {
                          const FileIcon = getFileIcon(resource.type)
                          return (
                            <div key={resource._id} className="flex items-center space-x-2 text-sm">
                              <FileIcon className="h-4 w-4 text-gray-400" />
                              <span className="truncate flex-1">{resource.name}</span>
                              <span className="text-xs text-gray-500">
                                {formatFileSize(resource.size)}
                              </span>
                            </div>
                          )
                        })}
                        {categoryResources.length > 3 && (
                          <div className="text-xs text-gray-500">
                            还有 {categoryResources.length - 3} 个文件...
                          </div>
                        )}
                        {categoryResources.length === 0 && (
                          <div className="text-xs text-gray-400">
                            暂无文件
                          </div>
                        )}
                      </div>
                    </CardContent>
                  </Card>
                )
              })}
            </div>
          </TabsContent>

          {/* 最近文件标签页 */}
          <TabsContent value="recent" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>最近上传的文件</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {resources
                    .sort((a, b) => new Date(b.uploadedAt).getTime() - new Date(a.uploadedAt).getTime())
                    .slice(0, 10)
                    .map((resource) => {
                      const FileIcon = getFileIcon(resource.type)
                      return (
                        <div key={resource._id} className="flex items-center justify-between p-3 border rounded-lg">
                          <div className="flex items-center space-x-3">
                            <FileIcon className="h-6 w-6 text-gray-400" />
                            <div>
                              <h4 className="font-medium">{resource.name}</h4>
                              <div className="flex items-center space-x-2 text-sm text-gray-500">
                                <span>{formatFileSize(resource.size)}</span>
                                <span>•</span>
                                <span>{resource.uploadedByName || '未知用户'}</span>
                                <span>•</span>
                                <span>{new Date(resource.uploadedAt).toLocaleDateString()}</span>
                              </div>
                            </div>
                          </div>
                          <div className="flex items-center space-x-2">
                            <Button variant="ghost" size="sm">
                              <Eye className="h-4 w-4" />
                            </Button>
                            <Button variant="ghost" size="sm">
                              <Download className="h-4 w-4" />
                            </Button>
                          </div>
                        </div>
                      )
                    })}
                  {resources.length === 0 && (
                    <div className="text-center py-8 text-gray-500">
                      <FolderOpen className="h-12 w-12 mx-auto mb-4 text-gray-400" />
                      <p>暂无最近文件</p>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  )
}